<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索用户信息区域 -->
      <el-row :gutter='20'>
        <el-col :span='10'>
          <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getUserList()"
            @change="getUserList()">
            <el-button @click="getUserList()" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户功能区域 -->
        <el-col :span='4'>
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表单区域 -->
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column label="编号" type="index">
        </el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row.mg_state}} 作用域插槽，获取一行内容打点使用mg_state-->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)" active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="权限">
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- {{scope.row.id}} -->
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" @click="showEditDialog(scope.row.id)"><i class="el-icon-edit"></i>
            </el-button>
            <!-- 删除用户信息 -->
            <el-button type="danger" size="mini" @click="deleteEditDialog(scope.row.id)"><i class="el-icon-delete"></i>
            </el-button>
            <!-- 设置 -->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" size="mini" @click="setRoles(scope.row)"><i class="el-icon-setting"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 4]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户信息对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" @close="addDialogClosed()">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="form.password" type="password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm(form)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="useslistModify" :rules="rulesModify" ref="useslistModify">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="useslistModify.username" autocomplete="off" disabled=""></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="useslistModify.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="useslistModify.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitModify(useslistModify)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配用户角色的对话框 -->
    <el-dialog title="分配用户角色" :visible.sync="setDialogVisible" width="50%" @close="closeRole()">
      <!-- <el-form :model="setRolesModify"> -->
      <div>
        <p>当前用户：{{setRolesModify.username}}</p>
        <p>当前角色：{{setRolesModify.role_name}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleID"  placeholder="请选择">
            <el-option v-for="item in roleslist" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>

        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义校验规则
    var checkEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱地址不能为空'))
      } else {
        if (reg.test(value)) return callback()
        callback(new Error('邮箱地址不合法'))
      }
    }
    // /^1[3456789]\d{9}$/ 手机号
    var checkMobile = (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/
      if (!value) {
        return callback(new Error('手机号码不能为空'))
      } else {
        if (reg.test(value)) return callback()
        callback(new Error('无效的手机号'))
      }
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 3
      },
      //   用户列表,用户总数
      userlist: [],
      total: 0,
      // 添加用户数据
      dialogFormVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单验证
      rules: {
        username: [{
          required: true,
          message: '请输入用户名称',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 9,
          message: '长度在 3 到 9 个字符',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '用户密码不能为空',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 16,
          message: '长度在 6 到 16 个字符',
          trigger: 'blur'
        }

        ],
        email: [{
          required: true,
          validator: checkEmail,
          trigger: 'blur'
        }],
        mobile: [{
          required: true,
          validator: checkMobile,
          trigger: 'blur'
        }]

      },
      // 修改用户对话框表单验证
      rulesModify: {
        email: [{
          required: true,
          validator: checkEmail,
          trigger: 'blur'
        }],
        mobile: [{
          required: true,
          validator: checkMobile,
          trigger: 'blur'
        }]
      },
      // 修改用户对话框是否显示
      editDialogVisible: false,
      // 修改用户信息对象
      useslistModify: {
        id: '',
        username: '',
        role_id: '',
        mobile: '',
        email: ''
      },
      // 分配用户角色
      setDialogVisible: false,
      setRolesModify: {
        id: '',
        role_id: '',
        username: ''
      },
      // 所有角色数据列表
      roleslist: [],
      // 已选中的角色id值
      selectRoleID: ''

    }
  },
  // 生命周期函数
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const {
        data: res
      } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log(this.userlist)
    },
    // 监听pagesize改变的事件
    handleSizeChange (newPageSize) {
      this.queryInfo.pagesize = newPageSize
      this.getUserList()
    },
    // 监听页码pagenum的改变
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听用户状态的改变,同步到后台数据库
    async userStateChanged (userInfo) {
      // console.log(userInfo)
      const str = 'users/' + (userInfo.id) + '/state/' + (userInfo.mg_state)
      const {
        data: res
      } = await this.$http.put(str)
      // console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败！')
      } else {
        this.$message.success('更新用户状态成功！')
      }
    },
    // 表单关闭重置表单内容
    addDialogClosed () {
      this.$refs.form.resetFields()
      // this.$refs.useslistModify.resetFields()
    },
    // 通过验证的数据同步到数据库，完成提交，不通过就出现警告信息
    submitForm (form) {
      this.$refs.form.validate(async valid => {
        // console.log(valid)
        if (valid) {
          // 验证通过
          const {
            data: res
          } = await this.$http.post('users', this.form)
          if (res.meta.status !== 201) return this.$message.error('用户创建失败')
          this.$message.success('用户创建成功！！！')
          this.dialogFormVisible = false
          this.getUserList()
        } else {
          return false
        }
      })
    },
    // 修改用户信息按钮的方法
    async showEditDialog (userid) {
      this.editDialogVisible = true
      // 根据id去数据库查询到信息，填充到页面
      const path = 'users/' + (userid)
      const {
        data: res
      } = await this.$http.get(path)
      if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
      this.useslistModify = res.data
    },
    // 提交修改的用户信息
    submitModify (userdata) {
      // 验证通过的才能进行提交
      this.$refs.useslistModify.validate(async valid => {
        if (valid) {
          // 发起网络请求
          const {
            data: res
          } = await this.$http.put('users/' + userdata.id, {
            email: userdata.email,
            mobile: userdata.mobile
          })
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error('更新用户信息失败')
          this.editDialogVisible = false
          this.getUserList()
          return this.$message.success(res.meta.msg)
        } else {
          return false
        }
      })
    },
    // 删除用户信息
    async deleteEditDialog (userid) {
      await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showCancelButton: true
      }).then(async () => {
        // 从数据库中也删除
        const {
          data: res
        } = await this.$http.delete('users/' + userid)
        console.log(res)
        if (res.meta.status === 200) {
          this.getUserList()
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分配用户角色
    async setRoles (userdata) {
      // 在显示这个窗口前，获取所有角色列表
      const {
        data: res
      } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.roleslist = res.data
      this.setDialogVisible = true
      this.setRolesModify = userdata
      // console.log(userdata)
      // this.$http.put('users/'+userdata.id+'/role',{rid:})
    },
    // 保存新的更改
    async saveRole () {
      if (!this.selectRoleID) return this.$message.error('您未作出任何修改操作')
      console.log(this.setRolesModify.id)
      const { data: res } = await this.$http.put('users/' + this.setRolesModify.id + '/role', { rid: this.selectRoleID })
      this.getUserList()
      this.setDialogVisible = false
      this.$message.success(res.meta.msg)
    },
    // 重置表单
    closeRole () {
      this.selectRoleID = ''
      this.setRolesModify = ''
    }
  }

}

</script>

<style lang="less" scoped>
  .el-breadcrumb {
    margin-bottom: 15px;
    font-size: 12px;
  }

  .el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important; // 给他最高权重
  }

  .el-table {
    margin-top: 20px;
    font-size: 12px;
  }

  .el-pagination {
    margin-top: 20px;
  }

</style>
